//
//  SWPhotoDetailViewController.swift
//  ChildStory
//
//  Created by linhan on 2016/11/21.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWPhotosDetailViewController: SWBaseViewController,UICollectionViewDataSource,UICollectionViewDelegate,PhotoEditorViewControllerDelegate,PulldownContainerDelegate
{
    weak var asset:SWAssetRecord?
    var index:Int = 0
    
    private var _size:CGSize = CGSize.zero
    private var _photos:[SWALPhoto] = []
    
    private var _picker:SWEventPicker?
    
    private var _dateLabel:UILabel = UILabel()
    private var _timeLabel:UILabel = UILabel()
    private var _imageView:UIImageView = UIImageView()
    private var _eventLabel:UILabel = UILabel()
    private var _bottomToolBar:UIView = UIView()
    private var _collectionView:UICollectionView?
    private var _deleteBtn:UIButton?
    private var _pulldownContainer:PulldownContainer = PulldownContainer()
    
    init(localIdentifiers:[String])
    {
        super.init(nibName: nil, bundle: nil)
        _photos = SWAssetsLibraryHelper.shared().fetchAssets(localIdentifiers: localIdentifiers)
    }
    
    init(photos:[SWALPhoto])
    {
        super.init(nibName: nil, bundle: nil)
        _photos = photos
    }
    
    init()
    {
        super.init(nibName: nil, bundle: nil)
        
        var assets = SWAssetsManager.sharedManager().assets
        assets.sort(by: {$0.addedTime > $1.addedTime})
        let ids:[String] = assets.flatMap({$0.localID}).filter({$0 != ""})
        _photos = SWAssetsLibraryHelper.shared().fetchAssets(localIdentifiers: ids)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        trace("DEINIT SWPhotosDetailViewController")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if _pulldownContainer.state != .closed
        {
            _pulldownContainer.close(false)
        }
    }
    
    private func setup()
    {
        automaticallyAdjustsScrollViewInsets = false
        
        let minEdge:CGFloat = min(view.width, view.height)
        _size = CGSizeMake(minEdge, minEdge)
        
        //导航栏日期
        createDateView()
        
        
        /////事件选择器
        createPickerView()
        
        //照片
        let Grid:CGFloat = 10
        let ItemSize:CGSize = CGSizeMake(minEdge, minEdge)
        let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.itemSize = CGSizeMake(ItemSize.width + Grid, ItemSize.height)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
        layout.scrollDirection = .horizontal
        
        
        _collectionView = UICollectionView(frame: CGRectMake(0, (view.height - ItemSize.height) * 0.5, ItemSize.width + Grid, ItemSize.height), collectionViewLayout: layout)
        _collectionView?.backgroundColor = UIColor.white
        _collectionView?.register(SWPhotosDetailCollectionCell.self, forCellWithReuseIdentifier: "SWPhotosDetailCollectionCell")
        _collectionView?.dataSource = self
        _collectionView?.delegate = self
        _collectionView?.isPagingEnabled = true
        _collectionView?.showsHorizontalScrollIndicator = false
        _collectionView?.showsVerticalScrollIndicator = false
        view.addSubview(_collectionView!)
        
        createBottomToolbar()
        
        if _photos.count > 0
        {
            _collectionView?.scrollToItem(at: IndexPath(row: max(index,0), section: 0), at: .left, animated: false)
            baseContainerDidEndScrolling(_collectionView!)
        }
    }
    
    //导航栏日期
    private func createDateView()
    {
        let dateView:UIView = UIView()
        dateView.frame = CGRectMake(0, 0, 100, 34)
        
        _dateLabel.textColor = UIColor.darkGray
        _dateLabel.font = UIFont.systemFont(ofSize: 14)
        _dateLabel.textAlignment = .center
        _dateLabel.frame = CGRectMake(0, 0, dateView.width, 18)
        
        _timeLabel.textColor = UIColor.darkGray
        _timeLabel.font = UIFont.systemFont(ofSize: 12)
        _timeLabel.textAlignment = .center
        _timeLabel.frame = CGRectMake(0, _dateLabel.bottom, dateView.width, 16)
        
        dateView.addSubview(_dateLabel)
        dateView.addSubview(_timeLabel)
        navigationItem.titleView = dateView
    }
    
    //事件选择器
    private func createPickerView()
    {
        let tapGesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(pickerViewTapped))
        let pickerView = UIView()
        pickerView.frame = CGRectMake(0, navigationBarBottom, view.width, 50)
        pickerView.backgroundColor = UIColor(white: 0.95, alpha: 1)
        pickerView.addGestureRecognizer(tapGesture)
        view.addSubview(pickerView)
        
        let line:UIView = UIView()
        line.backgroundColor = UIColor(hex: 0xe2e2e2)
        line.frame = CGRectMake(0, pickerView.height - 1, pickerView.width, 1)
        pickerView.addSubview(line)
        
        let pickerLabel:UILabel = UILabel()
        pickerLabel.text = "所属事件:"
        pickerLabel.textColor = UIColor(hex: 0x303030)
        pickerLabel.font = UIFont.systemFont(ofSize: 12)
        pickerLabel.sizeToFit()
        pickerLabel.center = CGPointMake(pickerLabel.width * 0.5 + 13, pickerView.height * 0.5)
        pickerView.addSubview(pickerLabel)
        
        let eventLabelHeight:CGFloat = 16
        _eventLabel.frame = CGRectMake(view.width * 0.5 - 30, (pickerView.height - eventLabelHeight) * 0.5, view.width * 0.5, eventLabelHeight)
        _eventLabel.font = UIFont.systemFont(ofSize: 12)
        _eventLabel.textColor = UIColor(hex: 0x303030)
        _eventLabel.textAlignment = .right
        pickerView.addSubview(_eventLabel)
        
        let indicatorView = UIImageView(image:UIImage(named:"photo_detail_btn_indicator"))
        indicatorView.center = CGPointMake(view.width - 16, pickerView.height * 0.5)
        pickerView.addSubview(indicatorView)
        
        let picker = SWEventPicker(frame: CGRectMake(0, 0, view.width, 150))
        picker.cancelCallback = {[weak self] in self?.pickerCancelCallback()}
        picker.chooseCallback = {[weak self] event in self?.pickerChooseCallback(event: event)}
        //picker.selectedEventID = asset?.eventID ?? ""
        _picker = picker
        
        _pulldownContainer.modelInsets = UIEdgeInsetsMake(navigationBarBottom, 0, 0, 0)
        _pulldownContainer.offset = CGPointMake(0, pickerView.bottom)
        _pulldownContainer.delegate = self
        _pulldownContainer.content = picker
    }
    
    private func createBottomToolbar()
    {
        let toolBarHeight:CGFloat = 50
        _bottomToolBar.frame = CGRectMake(0, view.height - toolBarHeight, view.width, toolBarHeight)
        _bottomToolBar.backgroundColor = UIColor(white: 0.92, alpha: 1)
        view.addSubview(_bottomToolBar)
        
        let line:UIView = UIView()
        line.backgroundColor = UIColor(hex: 0xe2e2e2)
        line.frame = CGRectMake(0, 0, _bottomToolBar.width, 1)
        _bottomToolBar.addSubview(line)
        
        let shareBtn:UIButton = UIButton(type: .custom)
        shareBtn.setImage(UIImage(named:"photo_detail_btn_share"), for: .normal)
        shareBtn.sizeToTouchEasy()
        shareBtn.center = CGPointMake(22, _bottomToolBar.bounds.center.y)
        shareBtn.addTarget(self, action: #selector(shareBtnTapped), for: .touchUpInside)
        _bottomToolBar.addSubview(shareBtn)
        
        let editBtn:UIButton = UIButton(type: .custom)
        editBtn.setImage(UIImage(named:"photo_detail_btn_edit"), for: .normal)
        editBtn.sizeToTouchEasy()
        editBtn.center = CGPointMake(_bottomToolBar.bounds.center.x, _bottomToolBar.bounds.center.y)
        editBtn.addTarget(self, action: #selector(editBtnTapped), for: .touchUpInside)
        _bottomToolBar.addSubview(editBtn)
        
        let deleteBtn:UIButton = UIButton(type: .custom)
        deleteBtn.setImage(UIImage(named:"photo_detail_btn_delete"), for: .normal)
        deleteBtn.sizeToTouchEasy()
        deleteBtn.center = CGPointMake(_bottomToolBar.width - 25, _bottomToolBar.bounds.center.y)
        deleteBtn.addTarget(self, action: #selector(deleteBtnTapped), for: .touchUpInside)
        _bottomToolBar.addSubview(deleteBtn)
        _deleteBtn = deleteBtn
    }
    
    private func removePhoto(_ photo:SWALPhoto, index:Int)
    {
        let localID:String = photo.localIdentifier
        self._photos.removeAtIndexSafely(index)
        self._collectionView?.deleteItems(at: [IndexPath(row: index, section: 0)])
        SWAssetsManager.sharedManager().removeAsset(localID: localID)
        NotificationCenter.default.post(name: NotificationName.DeleteAsset, object: nil, userInfo: [SWKey.localID:localID])
    }
    
    private func pickerCancelCallback()
    {
        //_dateTextField.resignFirstResponder()
    }
    
    private func pickerChooseCallback(event:SWKidEvent)
    {
        let aIndex:Int = index
        if let photo = _photos.valueAt(aIndex)
        {
            SWAssetsManager.sharedManager().changeAsset(localID: photo.localIdentifier, event: event)
        }
    }
    
    private func baseContainerDidEndScrolling(_ scrollView: UIScrollView)
    {
        let aIndex:Int = Int(scrollView.contentOffset.x / scrollView.width)
        if let photo = _photos.valueAt(aIndex)
        {
            if let aDate = photo.creationDate
            {
                let date:NSDate = aDate as NSDate
                _dateLabel.text = "\(date.month())月\(date.day())日"
                _timeLabel.text = "\(date.hour()):\(date.minute())"
            }
            
            let assets = SWAssetsManager.sharedManager().assets
            if let index = assets.index(where: {($0.localID ?? "") == photo.localIdentifier}),
               let asset = assets.valueAt(index), asset.classified
            {
                _eventLabel.text = asset.eventName
                _deleteBtn?.isHidden = false
            }
            else
            {
                _eventLabel.text = "未分类"
                _deleteBtn?.isHidden = true
            }
        }
        index = aIndex
    }
    
    private func share(channel:SWShareChannel)
    {
        if let photo = _photos.valueAt(index)
        {
            let localID:String = photo.localIdentifier
            SWAssetsLibraryHelper.shared().fetchOriginImage(localIdentifiers: [localID], options:nil, completeCallback: {[weak self] results in
                if let result = results.valueAt(0),
                    let image = result.image
                {
                    SWShareManager.sharedManager().share(image: image,channel: channel)
                }
            })
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return _photos.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell:SWPhotosDetailCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: "SWPhotosDetailCollectionCell", for: indexPath) as! SWPhotosDetailCollectionCell
        let index:Int = indexPath.row
        if let photo = _photos.valueAt(index)
        {
            cell.photo = photo
            //photo.fetchThumbnail()
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
    {
        
        
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView)
    {
        baseContainerDidEndScrolling(scrollView)
    }
    
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView)
    {
        baseContainerDidEndScrolling(scrollView)
    }
    
    func photoEditorViewController(_ controller:SWPhotoEditorViewController, didFinishProcessImage processedImage:UIImage, additionInfo info:[String:Any]?)
    {
        let index:Int = self.index
        SWAssetsLibraryHelper.shared().writeImageDataToAlbum(image: processedImage, albumName: SW.Config.DefaultAlbumName, completionHandler: {[weak self] result in
            
            if let newLocalID = result.localIdentifier,
               let oldLocalID = info?["localID"] as? String, newLocalID != "" && oldLocalID != ""
            {
                SWAssetsManager.sharedManager().replaceAsset(oldLocalID: oldLocalID, newLocalID: newLocalID)
                if let asset = SWAssetsLibraryHelper.shared().fetchAssets(localIdentifiers: [newLocalID]).valueAt(0)
                {
                    self?._photos.replaceSubrange(index...index, with: [asset])
                }
                
                SWNotificationCenter.post(name: NotificationName.AssetChanged, object: nil, userInfo: [SWKey.oldLocalID:oldLocalID, SWKey.newLocalID:newLocalID])
            }
            
            DispatchQueue.main.async {
                controller.close()
                self?._collectionView?.reloadItems(at: [IndexPath(row: index, section: 0)])
            }
            
        })
    }
    
    func photoEditorViewControllerDidCancel(_ controller: SWPhotoEditorViewController)
    {
        controller.close()
    }
    
    func willDismissPulldownContainer()
    {
        if let event = _picker?.selectedEvent
        {
            pickerChooseCallback(event: event)
            _eventLabel.text = event.title ?? ""
        }
    }
    
    
    @objc private func deleteBtnTapped()
    {
        let aIndex:Int = index
        if let photo = _photos.valueAt(aIndex)
        {
            ActionSheet.show("是否删除？", buttons: ["删除","保留"], closeHandler: {[weak self] buttonIndex in
                if buttonIndex == 0
                {
                    self?.removePhoto(photo, index: aIndex)
                }
            }, destructiveButtonIndex: 0, cancelButtonIndex: 1, container: nil)
        }
    }
    
    private func presentPhotoEditor(_ localID:String, image:UIImage)
    {
        let viewController = SWPhotoEditorViewController(origin: image)
        viewController.delegate = self
        viewController.additionInfo = ["localID":localID]
        let navigationController = SWBaseNavigationController(rootViewController: viewController)
        present(navigationController, animated: true, completion: nil)
    }
    
    @objc private func editBtnTapped()
    {
        if let photo = _photos.valueAt(index)
        {
            let localID:String = photo.localIdentifier
            SWAssetsLibraryHelper.shared().fetchOriginImage(localIdentifiers: [localID], options:nil, completeCallback: {[weak self] results in
                if let result = results.valueAt(0),
                   let image = result.image
                {
                    DispatchQueue.main.async {
                        self?.presentPhotoEditor(localID, image: image)
                    }
                }
            })
        }
    }
    
    @objc private func shareBtnTapped()
    {
        SWSharePresenter.instance.show {[weak self] action in
            self?.share(channel: SWShareAction.getShareChannelFormAction(action: action))
        }
    }
    
    @objc private func pickerViewTapped()
    {
        if _pulldownContainer.state == .closing || _pulldownContainer.state == .opening
        {
            return
        }
        
        if _pulldownContainer.state == .closed
        {
            _pulldownContainer.open()
        }
        else
        {
            _pulldownContainer.close()
        }
    }
    
    
}
